package com.webridge.plm.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class PDFEncrypt {

    // 缓存文件头信息-文件头信息
    public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();

    /**
     * Write to encrypt file header.
     */
    public static final String ENCRYPT_HEADER_INFO = "WINDCHILL_ENCRYPT_PWD2020";
    static {
        // images
        mFileTypes.put("FFD8FF", "jpg");
        mFileTypes.put("89504E47", "png");
        mFileTypes.put("47494638", "gif");
        mFileTypes.put("49492A00", "tif");
        mFileTypes.put("424D", "bmp");
        //
        mFileTypes.put("41433130", "dwg"); // CAD
        mFileTypes.put("38425053", "psd");
        mFileTypes.put("7B5C727466", "rtf"); // 日记本
        mFileTypes.put("3C3F786D6C", "xml");
        mFileTypes.put("68746D6C3E", "html");
        mFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件
        mFileTypes.put("D0CF11E0", "doc");
        mFileTypes.put("D0CF11E0", "xls");// excel2003版本文件
        mFileTypes.put("5374616E64617264204A", "mdb");
        mFileTypes.put("252150532D41646F6265", "ps");
        mFileTypes.put("255044462D312E", "pdf");
        mFileTypes.put("504B0304", "docx");
        mFileTypes.put("504B0304", "xlsx");// excel2007以上版本文件
        mFileTypes.put("52617221", "rar");
        mFileTypes.put("57415645", "wav");
        mFileTypes.put("41564920", "avi");
        mFileTypes.put("2E524D46", "rm");
        mFileTypes.put("000001BA", "mpg");
        mFileTypes.put("000001B3", "mpg");
        mFileTypes.put("6D6F6F76", "mov");
        mFileTypes.put("3026B2758E66CF11", "asf");
        mFileTypes.put("4D546864", "mid");
        mFileTypes.put("1F8B08", "gz");
    }

    /**
     * <p>
     * Title:main
     * </p>
     * <p>
     * Description: 测试
     * </p>
     * 
     * @param args
     * @throws Exception
     * @author Eric
     * @date 2018-05-23上午10:11:37
     */
    public static void main(String[] args) throws Exception {
        String workspace = "D:\\001Projects\\Others\\FileTest\\";
        String filePath = workspace + "srcfile\\" + "InfoEngine执行存储过程.pdf";

        String destFilePath = workspace + "encrypt\\" + "InfoEngine执行存储过程_encrypt10.pdf";
        encryptFile(filePath, destFilePath);
        String fileType = getFileType(destFilePath);
        System.out.println("After encrypt,file type:" + fileType);

    }

    /**
     * Encrypt file to a folder.
     * 
     * @param filePath
     * @param destFilePath
     */
    public static void encryptFile(String filePath, String destFilePath) {
        System.out.println("***************Encrypt File starts*****************");
        File srcFile = new File(filePath);
        File destFile = new File(destFilePath);
        try {
            FileInputStream fis = new FileInputStream(srcFile);
            final String fileType = getFileType(filePath);
            System.out.println("fileType:" + fileType);
            if ("PDF".equalsIgnoreCase(fileType)) {
                FileOutputStream fos = new FileOutputStream(destFile);

                 byte[]bufHeader = new byte[2];
                 int i = 0;
                 if(fis.read(bufHeader) != -1) {
                 fos.write(bufHeader );
                 }

                /**
                 * Insert Encrypt Info
                 */
                byte[] header = ENCRYPT_HEADER_INFO.getBytes();
                System.out.println("ENCRYPT_HEADER_INFO:" + header[0]);
                fos.write(header);// write to Encrypt File header.

                byte[] buf = new byte[1024];
                i = 0;
                while ((i = fis.read(buf)) != -1) {
                    fos.write(buf, 0, i);
                }

                fis.close();
                fos.close();

            } else {
                System.out.println("File isn't PDF.");
            }

            System.out.println("***************Encrypt File end*****************");

        } catch (IOException ie) {
            ie.printStackTrace();
        }

    }

    /**
     * Decrypt File to a folder
     * 
     * @param filePath
     * @param destFilePath
     */
    public static void decryptFile(String filePath, String destFilePath) {
        File srcFile = new File(filePath);
        File destFile = new File(destFilePath);
        try {
            FileInputStream fis = new FileInputStream(srcFile);
            final String fileType = getFileType(filePath);
            System.out.println("fileType:" + fileType);
            if ("PDF".equals(fileType)) {
                FileOutputStream fos = new FileOutputStream(destFile);
                byte[] header = ENCRYPT_HEADER_INFO.getBytes();
                fos.write(header);// write to Encrypt File header.
                byte[] buf = new byte[1024];
                int i = 0;
                while ((i = fis.read(buf)) != -1) {
                    fos.write(buf, 0, i);
                }
                fis.close();
                fos.close();
            } else {
                System.out.println("File isn't PDF.");
            }
        } catch (IOException ie) {
            ie.printStackTrace();
        }

    }

    /**
     * <p>
     * Title:getFileType
     * </p>
     * <p>
     * Description: 根据文件路径获取文件头信息
     * </p>
     * 
     * @param filePath
     *            文件路径
     * @return 文件头信息
     * @author Eric
     * @date 2018-05-23上午10:06:40
     */
    public static String getFileType(String filePath) {
        String fileType = "";
        String fileHeader = getFileHeader(filePath);
        System.out.println("FileHeader:" + fileHeader); // 返回十六进制 如：504B0304
        // System.out.println(mFileTypes.get(getFileHeader(filePath))); //xlsx
        Set<String> fileHeaderSet = mFileTypes.keySet();
        Iterator it = fileHeaderSet.iterator();
        while (it.hasNext()) {
            String header = (String) it.next();
            // System.out.println(header);
            if (header.startsWith(fileHeader)) {
                fileType = mFileTypes.get(header);

                break;
            }
        }
        return fileType;
    }

    /**
     * <p>
     * Title:getFileTypeByFileInputStream
     * </p>
     * <p>
     * Description: 根据文件流获取文件头信息
     * </p>
     * 
     * @param is
     *            文件流
     * @return 文件头信息
     * @author Eric
     * @date 2018-05-23上午10:23:10
     */
    public static String getFileTypeByFileInputStream(FileInputStream is) {
        return mFileTypes.get(getFileHeaderByFileInputStream(is));
    }

    /**
     * <p>
     * Title:getFileHeader
     * </p>
     * <p>
     * Description: 根据文件路径获取文件头信息
     * </p>
     * 
     * @param filePath
     *            文件路径
     * @return 十六进制文件头信息
     * @author Eric
     * @date 2018-05-23上午10:08:16
     */
    public static String getFileHeader(String filePath) {
        FileInputStream is = null;
        String value = null;
        try {
            is = new FileInputStream(filePath);
            byte[] b = new byte[4];
            /*
             * int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length
             * 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
             * 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
             */
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return value;
    }

    /**
     * <p>
     * Title:getFileHeaderByFileInputStream
     * </p>
     * <p>
     * Description: 根据文件流获取文件头信息
     * </p>
     * 
     * @param is
     *            文件流
     * @return 十六进制文件头信息
     * @author Eric
     * @date 2018-05-23上午10:20:27
     */
    public static String getFileHeaderByFileInputStream(FileInputStream is) {
        String value = null;
        try {
            byte[] b = new byte[4];
            /*
             * int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length
             * 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
             * 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
             */
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
            System.out.println("File header:" + value);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return value;
    }

    /**
     * <p>
     * Title:bytesToHexString
     * </p>
     * <p>
     * Description: 将要读取文件头信息的文件的byte数组转换成string类型表示
     * </p>
     * 
     * @param src
     *            要读取文件头信息的文件的byte数组
     * @return 文件头信息
     * @author Eric
     * @date 2018-05-23上午10:09:56
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
        // System.out.println(builder.toString());
        return builder.toString();
    }

}
